package com.wiz.netty.service;

import io.netty.channel.ChannelHandlerContext;

import org.apache.commons.lang3.StringUtils;

import com.google.common.primitives.Bytes;
import com.wiz.common.NettyConstant;
import com.wiz.common.util.ByteUtil;
import com.wiz.data.factory.MessageDataFactory;
import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.service.LoginService;
import com.wiz.web.vo.type.ServiceType;

public abstract class NettyThread implements NettyConstant{

	protected ChannelHandlerContext ctx;
	protected NettyMessageTO.MessageContent message;
	protected ServiceManager serviceManager;
	protected NettyXmlParseFactory wizXmlFactory;
	protected MessageDataFactory messageDataFactory = MessageDataFactory.getInstance();

	public ChannelHandlerContext getCtx() {
		return ctx;
	}

	public void setCtx(ChannelHandlerContext ctx) {
		this.ctx = ctx;
	}

	public NettyMessageTO.MessageContent getMessage() {
		return message;
	}

	public void setMessage(NettyMessageTO.MessageContent message) {
		this.message = message;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public NettyXmlParseFactory getWizXmlFactory() {
		return wizXmlFactory;
	}

	public void setWizXmlFactory(NettyXmlParseFactory wizXmlFactory) {
		this.wizXmlFactory = wizXmlFactory;
	}

	/**
	 * ---------------------逻辑方法 分割线---------------------------------
	 */

	/**
	 * 
	 * @param mac
	 * @param mab
	 * @param stationNo
	 * @return
	 * @throws Exception
	 */
	protected boolean checkDynamicMac(byte[] mac, byte[] mab, String stationId) throws Exception{
		LoginService loginService = (LoginService) serviceManager.getService(ServiceType.LOGIN.getId());
		String dynamicKey = loginService.getDynamicKey(stationId);
		if(StringUtils.isBlank(dynamicKey)){
			return false;
		}
		byte[] checkMac = messageDataFactory.getMac(mab, dynamicKey.getBytes());
		if (Bytes.indexOf(mac, checkMac) == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 验证静态mac
	 * @param mac
	 * @param mab
	 * @param stationNo
	 * @return
	 * @throws Exception
	 */
	protected boolean checkStaticMac(byte[] mac, String stationId){
		LoginService loginService = (LoginService) serviceManager.getService(ServiceType.LOGIN.getId());
		String staticKey = loginService.getStaticKey(stationId);
		byte[] checkMac = ByteUtil.HexString2Bytes(staticKey);
		if (Bytes.indexOf(mac, checkMac) == 0) {
			return true;
		}
		return false;
	}
}
